<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="handleBack">
          <el-icon>
            <ArrowLeft/>
          </el-icon>
          返回列表
        </el-button>
        <h1 class="page-title">订单详情</h1>
      </div>
      <div class="header-right">
        <el-tag
            v-if="orderDetail"
            :type="getOrderStatusInfo(orderDetail.status).type"
            size="large"
        >
          {{ getOrderStatusInfo(orderDetail.status).text }}
        </el-tag>
      </div>
    </div>

    <div v-loading="loading" class="order-detail">
      <div v-if="orderDetail" class="detail-content">
        <!-- 订单基本信息 -->
        <el-card class="info-card" shadow="hover">
          <template #header>
            <span class="card-title">订单信息</span>
          </template>

          <el-descriptions v-if="orderDetail" :column="3" border>
            <el-descriptions-item label="订单号">
              {{ orderDetail.orderNo }}
            </el-descriptions-item>

            <el-descriptions-item label="订单状态">
              <el-tag :type="getOrderStatusInfo(orderDetail.status).type">
                {{ getOrderStatusInfo(orderDetail.status).text }}
              </el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="下单时间">
              {{ formatDateTime(orderDetail.createTime) }}
            </el-descriptions-item>

            <el-descriptions-item label="用户信息">
              {{ orderDetail.username }}
            </el-descriptions-item>

            <el-descriptions-item label="支付方式">
              {{ getPaymentTypeName(orderDetail.paymentType) }}
            </el-descriptions-item>

            <el-descriptions-item label="支付状态">
              <el-tag :type="getPaymentStatusInfo(orderDetail.paymentStatus).type">
                {{ getPaymentStatusInfo(orderDetail.paymentStatus).text }}
              </el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="支付时间">
              {{ formatDateTime(orderDetail.paymentTime) || '-' }}
            </el-descriptions-item>

            <el-descriptions-item label="发货状态">
              <el-tag :type="getDeliveryStatusInfo(orderDetail.deliveryStatus).type">
                {{ getDeliveryStatusInfo(orderDetail.deliveryStatus).text }}
              </el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="发货时间">
              {{ formatDateTime(orderDetail.deliveryTime) || '-' }}
            </el-descriptions-item>

            <el-descriptions-item label="收货时间">
              {{ formatDateTime(orderDetail.receiveTime) || '-' }}
            </el-descriptions-item>

            <el-descriptions-item label="过期时间">
              {{ formatDateTime(orderDetail.expireTime) || '-' }}
            </el-descriptions-item>

            <el-descriptions-item label="订单备注">
              {{ orderDetail.remark || '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 收货信息 -->
        <el-card class="info-card" shadow="hover">
          <template #header>
            <span class="card-title">收货信息</span>
          </template>

          <el-descriptions v-if="orderDetail" :column="2" border>
            <el-descriptions-item label="收货人">
              {{ orderDetail.receiverName }}
            </el-descriptions-item>

            <el-descriptions-item label="联系电话">
              {{ orderDetail.receiverPhone }}
            </el-descriptions-item>

            <el-descriptions-item :span="2" label="收货地址">
              {{ orderDetail.receiverAddress }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 商品信息 -->
        <el-card class="info-card" shadow="hover">
          <template #header>
            <span class="card-title">商品信息</span>
          </template>

          <el-table :data="orderDetail?.orderItems || []" style="width: 100%">
            <el-table-column label="商品图片" width="100">
              <template #default="{ row }">
                <img
                    v-if="row.productImage"
                    :src="row.productImage"
                    alt="商品图片"
                    class="product-image"
                />
                <el-icon v-else color="#ccc" size="40">
                  <Picture/>
                </el-icon>
              </template>
            </el-table-column>

            <el-table-column label="商品名称" min-width="200" prop="productName"/>

            <el-table-column label="单价" width="120">
              <template #default="{ row }">
                <span class="price">¥{{ row.unitPrice }}</span>
              </template>
            </el-table-column>

            <el-table-column label="数量" prop="quantity" width="80"/>

            <el-table-column label="小计" width="120">
              <template #default="{ row }">
                <span class="price">¥{{ row.totalPrice }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 金额信息 -->
        <el-card class="info-card" shadow="hover">
          <template #header>
            <span class="card-title">金额信息</span>
          </template>

          <div v-if="orderDetail" class="amount-info">
            <div class="amount-row">
              <span class="label">商品总额：</span>
              <span class="value">¥{{ orderDetail.totalAmount }}</span>
            </div>
            <div class="amount-row">
              <span class="label">实付金额：</span>
              <span class="value total-amount">¥{{ orderDetail.actualAmount }}</span>
            </div>
          </div>
        </el-card>

        <!-- 操作按钮 -->
        <div v-if="orderDetail" class="action-buttons">
          <el-button
              v-if="orderDetail.status === 2 && orderDetail.paymentStatus === 1"
              type="success"
              @click="handleDeliver"
          >
            发货
          </el-button>

          <el-button
              v-if="orderDetail.status === 1"
              type="warning"
              @click="handleCancel"
          >
            取消订单
          </el-button>

          <el-button
              type="info"
              @click="handleRemark"
          >
            修改备注
          </el-button>
        </div>
      </div>

      <div v-else-if="!loading" class="no-data">
        <el-empty description="订单不存在或已被删除"/>
      </div>
    </div>

    <!-- 发货对话框 -->
    <DeliveryDialog
        v-model="deliveryDialogVisible"
        :order="orderDetail"
        @success="handleDeliverySuccess"
    />

    <!-- 备注对话框 -->
    <RemarkDialog
        v-model="remarkDialogVisible"
        :order="orderDetail"
        @success="handleRemarkSuccess"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {ArrowLeft, Picture} from '@element-plus/icons-vue'
import {useOrderStore} from '@/store/order'
import {formatDateTime} from '@/utils'
import DeliveryDialog from './DeliveryDialog.vue'
import RemarkDialog from './RemarkDialog.vue'

// 路由
const route = useRoute()
const router = useRouter()

// Store
const orderStore = useOrderStore()

// 响应式数据
const deliveryDialogVisible = ref(false)
const remarkDialogVisible = ref(false)

// 计算属性
const orderDetail = computed(() => orderStore.currentOrder)
const loading = computed(() => orderStore.loading)

// 方法
const handleBack = () => {
  router.push('/orders')
}

const getOrderStatusInfo = (status) => {
  return orderStore.getOrderStatusInfo(status)
}

const getPaymentStatusInfo = (status) => {
  return orderStore.getPaymentStatusInfo(status)
}

const getDeliveryStatusInfo = (status) => {
  return orderStore.getDeliveryStatusInfo(status)
}

const getPaymentTypeName = (type) => {
  const typeMap = {
    1: '微信支付',
    2: '支付宝支付'
  }
  return typeMap[type] || '未知'
}

const handleDeliver = () => {
  deliveryDialogVisible.value = true
}

const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
        `确定要取消订单 "${orderDetail.value.orderNo}" 吗？`,
        '确认取消',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await orderStore.cancelOrder(orderDetail.value.id, {reason: '管理员取消'})
    ElMessage.success('订单取消成功')

    // 重新加载订单详情
    await loadOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消失败，请重试')
    }
  }
}

const handleRemark = () => {
  remarkDialogVisible.value = true
}

const handleDeliverySuccess = () => {
  deliveryDialogVisible.value = false
  loadOrderDetail()
}

const handleRemarkSuccess = () => {
  remarkDialogVisible.value = false
  loadOrderDetail()
}

const loadOrderDetail = async () => {
  const orderId = route.params.id
  if (!orderId) {
    ElMessage.error('订单ID不存在')
    handleBack()
    return
  }

  try {
    await orderStore.getOrderDetail(orderId)
  } catch (error) {
    console.error('加载订单详情失败:', error)
    ElMessage.error('加载订单详情失败')
    handleBack()
  }
}

// 生命周期
onMounted(() => {
  loadOrderDetail()
})
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
}

.order-detail {
  min-height: 400px;
}

.info-card {
  margin-bottom: 20px;
}

.card-title {
  font-weight: 600;
  font-size: 16px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.price {
  color: #e6a23c;
  font-weight: 600;
}

.amount-info {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
}

.amount-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.amount-row:last-child {
  margin-bottom: 0;
}

.amount-row .label {
  font-size: 14px;
  color: #606266;
}

.amount-row .value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.total-amount {
  color: #e6a23c !important;
  font-size: 18px !important;
}

.action-buttons {
  text-align: center;
  margin-top: 30px;
}

.action-buttons .el-button {
  margin: 0 8px;
}

.no-data {
  text-align: center;
  padding: 60px 0;
}
</style>
